#!/bin/bash

source /build/venv/bin/activate

# get appliance name
if [ $# -eq 0 ]; then
    APPLIANCE="/tmp/build/images/appliance.kiwi"
    echo "Using default $APPLIANCE"
else
    APPLIANCE=$1
fi

# complete appliance path
if [[ "${APPLIANCE}" != "/"* ]]; then
    # handle relative path
    if [ ! -f "${APPLIANCE}" ]; then
        # relative path from current folder does not exist
        # use relative path in workspace images folder
        APPLIANCE="/tmp/build/images/$APPLIANCE"
    fi
fi

APPLIANCE=$(realpath $APPLIANCE)

if [ ! -f "$APPLIANCE" ]; then
    echo "Appliance file $APPLIANCE not found!"
    exit 1
fi

echo "Building appliance ${APPLIANCE}"

# clean old result folder
sudo rm -rf /tmp/result_image

FILENAME="$(basename "${APPLIANCE}")"

echo "Appliance file ${FILENAME}"

export APPLIANCE

# check if user berrymill config exists
BUILD_FOLDER=$(dirname "${APPLIANCE}")
if [ -f "${BUILD_FOLDER}/berrymill.conf" ]; then
    # use config from specific image folder
    BERRYMILL_CFG="${BUILD_FOLDER}/berrymill.conf"
else
    if [ -f "/workspace/images/berrymill.conf" ]; then
        # use config form workspace images folder
        BERRYMILL_CFG="/workspace/images/berrymill.conf"
    else
        # use default config
        BERRYMILL_CFG="/etc/berrymill/berrymill.conf"
    fi
fi

export BERRYMILL_CFG
